package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

@Slf4j
@Component
public class CacheClient {

    private final StringRedisTemplate stringRedisTemplate;

    public CacheClient(StringRedisTemplate redisTemplate) {
        this.stringRedisTemplate = redisTemplate;
    }

    public void set(String key, Object value, long timeout, TimeUnit unit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), timeout, unit);
    }

    public void setWithLogicExpire(String key, Object value, long timeout, TimeUnit unit){
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(timeout)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    public <R, ID> R queryByIdWithPassThrough(String keyPrefix,
                                              ID id,
                                              Class<R> type,
                                              Function<ID, R> dbFallback,
                                              Long time,
                                              TimeUnit unit) {
        String key = keyPrefix + id;
        // 从redis查询商铺缓存
        String json = stringRedisTemplate.opsForValue().get(key);
        // 判断是否存在
        if (StrUtil.isNotBlank(json)) {
            // 存在直接返回
            R r = JSONUtil.toBean(json, type);
            return  r;
        }

        //判断命中的是否是空值
        if (json != null) {
            return null;
        }

        // 不存在，根据id查询数据库
        R r = dbFallback.apply(id);

        // 不存在，返回错误
        if (r == null) {
            //将空值写入redis---->防止缓存穿透
            stringRedisTemplate.opsForValue().set(key, "", time, unit);
            return null;
        }

        // 存在，写入redis
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(r), time, unit);

        return r;
    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    public <R, ID> R queryByIdWithLogicExpire(String keyPrefix,
                                              ID id,
                                              Class<R> type,
                                              Function<ID, R> dbFallback,
                                              Long time,
                                              TimeUnit unit) {
        String key = keyPrefix + id;
        // 从redis查询商铺缓存
        String json = stringRedisTemplate.opsForValue().get(key);
        // 判断是否存在
        if (StrUtil.isBlank(json)) {
            return null;
        }

        //命中，需要先把json反序列化
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        JSONObject data = (JSONObject) redisData.getData();
        R r = JSONUtil.toBean(data, type);
        LocalDateTime expireTime = redisData.getExpireTime();
        // 判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            // 未过期，直接返回
            return r;
        }

        // 已过期，缓存重建
        // 获取互斥锁
        String lockkey = LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockkey);
        try {
            if (isLock) {
                // 成功，开启独立线程，实现缓存重建查询数据库
                // TODO  注意：获取锁成功后要再次检查redis缓存是否过期。如果缓存存在，则无需重建缓存
                CACHE_REBUILD_EXECUTOR.submit(() -> {
                    R r1 = dbFallback.apply(id);
                    setWithLogicExpire(key, r1, time, unit);
                });
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            unLock(lockkey);
        }
        //返回过期商铺信息
        return r;
    }

    //获取锁
    public boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10L, TimeUnit.MINUTES);
        return BooleanUtil.isTrue(flag);
    }

    // 释放锁
    public void unLock(String key) {
        stringRedisTemplate.delete(key);
    }


}
